#include <iostream>
#include <dirent.h>
#include <stdio.h>
#include <string.h>
#include <malloc.h>
#include <vector>
#include <map>
#include <stdlib.h>
#include <string>
#include <sstream>
#include <fstream>

int choice = 0;
/*
 Permet de séparer le nom des fichiers appliqué et leur file
 */
int Split(std::vector<std::string>& vecteur, std::string chaine,
		char separateur) {
	vecteur.clear();
	std::string::size_type stTemp = chaine.find(separateur);
	while (stTemp != std::string::npos) {
		vecteur.push_back(chaine.substr(0, stTemp));
		chaine = chaine.substr(stTemp + 1);
		stTemp = chaine.find(separateur);
	}
	vecteur.push_back(chaine);
	return vecteur.size();
}
/*
{"bedroom;",},
{"CALsuburb;",},
{"kitchen;",},
{"livingroom;",},
{"MITcoast;",},
{"MITforest;",},
{"MIThighway;",},
{"MITinsidecity;",},
{"MITmountain;",},
{"MITopencountry;",},
{"MITstreet;",},
{"MITtallbuilding;",},
{"PARoffice;",}
*/

void createCSVFile(const char* dir, std::ofstream& ofs1, std::ofstream& ofs2, int fold) {
	std::map<std::string, int>	folder_number = {
			{"bedroom",0},
			{"CALsuburb",1},
			{"kitchen",2},
			{"livingroom",3},
			{"MITcoast",4},
			{"MITforest",5},
			{"MIThighway",6},
			{"MITinsidecity",7},
			{"MITmountain",8},
			{"MITopencountry",9},
			{"MITstreet",10},
			{"MITtallbuilding",11},
			{"PARoffice",12} };
	DIR *pDIR;
	struct dirent *entry;
	pDIR = opendir(dir);
	if (!pDIR)
		return;
	while ((entry = readdir(pDIR))) {
		if (strcmp(entry->d_name, ".") != 0
				&& strcmp(entry->d_name, "..") != 0) {
			std::string path = std::string(dir);
			std::string name = path + "/" + std::string(entry->d_name);
			if (std::string(entry->d_name).find(".jpg", 0)
					!= std::string::npos) {
				std::vector<std::string> dirs;
				Split(dirs, path, '/');
				int size = dirs.size();
				std::string folder_name = dirs[size - 1].substr(0, std::string::npos);
				int _num = folder_number.at(folder_name);
				std::ostringstream oss;
				oss << _num;
				name += ";" + oss.str();
				if (choice % 3 != fold)
					ofs1 << name << std::endl;
				else
					ofs2 << name << std::endl;
				choice++;
			}
			createCSVFile(name.c_str(), ofs1, ofs2, fold);
		}
	}
	closedir(pDIR);
}

int maina(int argc, char *argv[]) {
	std::ofstream ofs1(argv[2]);
	std::ofstream ofs2(argv[3]);
	int fold = atoi(argv[4]);
	createCSVFile(argv[1], ofs1, ofs2, fold);
	return 0;
}
